 <template>
  <div style="min-height: 500px" class="row q-col-gutter-x-md">
    <div class="col-lg-3 col-md-5" style="height:800px;overflow:auto;">
      <q-card>
        <q-card-section>
          <q-tree
            ref="orgTree"
            :nodes="data"
            node-key="id"
            label-key="name"
            :selected.sync="nodeSelected"
            selected-color="primary"
            :expanded.sync="nodeExpanded"
          >
            <template v-slot:header-root="prop">
              <div class="row items-center" style="width:100%;" id="treeName">
                <q-badge transparent align="middle" color="primary">
                  菜单
                </q-badge>
                <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.kjCode + ' - ' + prop.node.name">{{ prop.node.kjCode + ' - ' + prop.node.name }}</div>
              </div>
              <!-- <q-popup-proxy context-menu>
                <q-list dense class="text-grey">
                  <q-item clickable v-close-popup @click="edit(prop.node)">
                    <q-item-section>
                      <q-item-label>修改</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-popup-proxy> -->
            </template>
            <template v-slot:header-header="prop">
              <div class="row items-center" style="width:100%;flex-wrap:nowrap">
                <q-badge transparent align="middle" color="orange">
                  tab
                </q-badge>
                <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.name">{{ prop.node.name }}</div>
              </div>
            </template>
          </q-tree>
        </q-card-section>
      </q-card>
    </div>
    <div class="col-lg-9 col-md-7">
      <q-table
        class="bg-white"
        dense
        :data="dataPlan"
        :columns="columnsPlan"
        row-key="id"
        separator="cell"
        table-class="h-custom"
        :visible-columns="visibleColumnsPlan"
        :filter="searchForm"
        selection="multiple"
        :selected.sync="selected"
        :pagination.sync="pagination"
        :rows-per-page-options="[3, 5, 10, 20]"
        no-data-label="暂无数据"
        @request="listGet"
      >
        <!-- <template v-slot:top-left="props">
          <div class="q-py-sm">
            <q-btn  size="sm" color="light-blue" :label="$t('上传附件')" @click="add"/>
          </div>
        </template> -->
        <template v-slot:top-right="props">
          <q-select
            v-model="visibleColumnsPlan"
            multiple
            borderless
            options-dense
            :display-value="$t('显示列')"
            emit-value
            map-options
            :options="columnsPlan"
            option-value="name"
            class="q-mx-lg"
          >
            <template v-slot:option="scope">
              <q-item
                v-bind="scope.itemProps"
                v-on="scope.itemEvents"
                v-if="!scope.opt.required"
              >
                <q-item-section avatar>
                  <q-toggle color="blue" v-model="visibleColumnsPlan" :val="scope.opt.name" />
                </q-item-section>
                <q-item-section style="min-width:60px">
                  {{ scope.opt.label }}
                </q-item-section>
              </q-item>
            </template>
          </q-select>
          <q-toggle
            v-model="searchToggle"
            left-label
            label="搜索"
            color="blue"
            checked-icon="check"
            unchecked-icon="clear"
            keep-color
          />
          <q-btn
            flat round dense
            :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
            @click="props.toggleFullscreen"
            class="q-ml-md"
          />
        </template>
        <template v-if="searchToggle" v-slot:top-row="props">
          <q-tr :props="props">
            <q-td>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
              <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchForm })"/>
              <q-input dense outlined v-model="searchForm[col.name]" v-else/>
            </q-td>
          </q-tr>
        </template>
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th>
              <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
            </q-th>
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              {{ col.label }}
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td width="52">
              <q-checkbox dense v-model="props.selected" />
            </q-td>
            <q-td key="action" :props="props">
              <q-btn-dropdown
                color="blue"
                size="sm"
                dense
                menu-anchor="bottom left"
                menu-self="top left"
                content-class="text-grey"
                icon="settings">
                <q-list dense>
                  <q-item clickable v-close-popup @click="delRow(props.row)">
                    <q-item-section>
                      <q-item-label>删除</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-btn-dropdown>
            </q-td>
            <!-- <q-td key="code" :props="props">{{ props.row.code }}</q-td> -->
            <q-td key="name" :props="props" class="h-td-maxwidth ellipsis">
              <a v-if="props.row.remoteUrl != null" @click="goTo(props)" style="border-bottom:1px solid #0000ee;color:#0000ee;cursor:pointer;" title="预览">{{ props.row.name }}</a>
              <span v-else>暂无预览地址</span>
            </q-td>
            <q-td key="fileSize" :props="props">{{ props.row.fileSize }}</q-td>
            <q-td key="fileType" :props="props">{{ props.row.fileType }}</q-td>
            <q-td key="url" :props="props" class="h-td-maxwidth ellipsis">
              <a v-if="props.row.remoteUrl != null" :href=props.row.remoteUrl :download="props.row.name">下载</a>
              <!-- <a v-if="props.row.props.row.fileType != txt" :href=props.row.remoteUrl :download="props.row.name">下载</a> -->
              <!-- <a v-if="props.row.remoteUrl != null" href=props.row.remoteUrl :download="props.row.name">下载</a> -->
              <span v-else>暂无下载地址</span>
            </q-td>
            <q-td key="createUserName" :props="props">{{ props.row.createUserName }}</q-td>
            <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
            <q-td key="remark" :props="props">{{ props.row.remark }}</q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="props">
          <q-pagination
            v-model="pagination.page"
            color="blue"
            :max-pages="5"
            :max="pages"
            :boundaryLinks="true"
            :directionLinks="true"
          />
          共 {{ total }} 条
        </template>
      </q-table>
    </div>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw">
        <q-bar class="bg-white q-py-lg">
          <strong>上传附件</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <div>上传附件</div>
              <!-- <q-uploader
                :url="uploadUrl"
                multiple
                label="name"
                @uploaded="fileUploaded"
                :headers="header"
                @upload
                batch
                style="max-width: 300px"
              /> -->
              <q-uploader
                :form-fields="dataFiles"
                hide-underline
                no-thumbnails
                ref="bomUploader"
                color="secondary"
                name="file"
                field-name="file"
                @add="$refs['bomUploader'].upload()"
                @uploaded="fileUploaded"
                :headers="header"
                :url="uploadUrl"></q-uploader>
            </div>
          </div>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <!-- <q-btn flat label="保存" color="primary" :loading="loadingSave"/> -->
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
 </template>

<script>
import { transformToTreeFormat } from 'src/utils/fns'
export default {
  name: 'File',
  data () {
    return {
      // 上传
      dataFiles: [
        { name: 'a', value: '11111111' }
      ],
      uploadUrl: 'http://118.178.94.163:6080/uploadMtfile',
      header: [
        {
          name: 'Accept',
          value: 'application/x-www-form-urlencoded;charset=utf-8'
        }
      ],
      // 弹框
      addOrEditDialog: false,
      maximizedToggle: false,
      // 菜单
      nodeSelected: [],
      nodeExpanded: [],
      nodeTicked: [],
      ids: [],
      selected: [],
      searchToggle: false,
      dataPlan: [],
      searchForm: {
        name: '',
        fileSize: '',
        fileType: '',
        url: '',
        createUserName: '',
        createTime: '',
        remark: ''
      },
      visibleColumnsPlan: [
        'action',
        'name',
        'fileSize',
        'fileType',
        'url',
        'createUserName',
        'createTime',
        'remark'
      ],
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      columnsPlan: [
        { name: 'action', align: 'center', label: '操作' },
        // { name: 'code', required: true, label: '编码', align: 'left', field: 'code', sortable: true },
        { name: 'name', required: true, label: '名称', align: 'left', field: 'name', sortable: true },
        { name: 'fileSize', label: '文件大小', align: 'left', field: 'fileSize', sortable: true },
        { name: 'fileType', label: '文件类型', align: 'left', field: 'fileType', sortable: true },
        { name: 'url', label: '下载', align: 'left', field: 'url', sortable: true },
        { name: 'createUserName', label: '创建人', align: 'left', field: 'createUserName', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true },
        { name: 'remark', field: 'remark', align: 'left', label: '说明', sortable: true }
      ]
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    'nodeSelected' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    }
  },
  created () {
    this.getMenu()
  },
  methods: {
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除附件：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          baseUrl: 'http://118.178.94.163:6080',
          method: 'get',
          url: `/deleteSysFile?id=${row.id}`,
          emulateJSON: true,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    add () {
      this.addOrEditDialog = true
    },
    fileUploaded (file, xhr) {
      var res = JSON.parse(xhr.response)
      if (res.success) {
        this.$q.notify({
          message: '上传成功',
          type: 'positive',
          icon: 'done',
          timeout: 1000,
          position: 'top-right'
        })
      }
    },
    goTo (props) {
      window.open('http://118.178.94.163:6080/mtPreview?url=' + props.row.remoteUrl, '_blank')
    },
    getMenu () {
      this.data = []
      // let arr = [{typeIds: 0}]
      //   typeIds: 0,
      //   typeIds: 2
      // }
      this.$api({
        method: 'post',
        url: '/mdm/permission/query',
        params: {
          typeIds: '0'
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          data.forEach(item => {
            this.ids.push(item.id)
            if (item.type === 0) {
              item.header = 'root'
            } else if (item.type === 2) {
              item.header = 'header'
            }
            // item.name = String(item.code) + String(item.name)
          })
          this.nodeExpanded = this.ids
          this.data = transformToTreeFormat(data, 'id', 'parentId', 'children')
          console.log(this.data)
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        baseUrl: 'http://118.178.94.163:6080',
        method: 'post',
        url: '/sys/file/query',
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          menuId: this.nodeSelected,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.total = data.total
          this.dataPlan = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    }
  }
}
</script>

<style lang="stylus" scoped>
#treeName
  flex-wrap nowrap
</style>
